<template>
  <view class="user-container">
    <!-- 搜索区域 -->
    <view class="search-box">
      <view class="search-form">
        <view class="search-item">
          <text class="label">用户名称</text>
          <input v-model="queryParams.userName" type="text" placeholder="请输入用户名称" @confirm="handleQuery" />
        </view>
        <view class="search-item">
          <text class="label">手机号码</text>
          <input v-model="queryParams.phonenumber" type="text" placeholder="请输入手机号码" @confirm="handleQuery" />
        </view>
        <view class="search-item">
          <text class="label">状态</text>
          <picker @change="handleStatusChange" :value="statusIndex" :range="statusOptions" range-key="label">
            <view class="picker-box">
              <text :class="{ 'placeholder': !queryParams.status }">
                {{ statusOptions[statusIndex].label }}
              </text>
              <uni-icons type="bottom" size="12" color="#909399"></uni-icons>
            </view>
          </picker>
        </view>
      </view>
      <view class="btn-group">
        <view class="btn search-btn" @tap="handleQuery">
          <uni-icons type="search" size="14" color="#fff"></uni-icons>
          <text>搜索</text>
        </view>
        <view class="btn reset-btn" @tap="resetQuery">
          <uni-icons type="refresh" size="14" color="#606266"></uni-icons>
          <text>重置</text>
        </view>
        <view class="btn add-btn" @tap="handleAdd">
          <uni-icons type="plusempty" size="14" color="#fff"></uni-icons>
          <text>新增</text>
        </view>
      </view>
    </view>

    <!-- 用户列表 -->
    <view class="user-list" v-if="userList.length > 0">
      <view v-for="(item, index) in userList" :key="index" class="user-item" @click="handleViewDetail(item)">
        <view class="user-info">
          <image class="avatar" :src="item.avatar || defaultAvatar" mode="aspectFill"></image>
          <view class="info-content">
            <view class="name-row">
              <text class="username">{{ item.userName }}</text>
              <text class="nickname">{{ item.nickName }}</text>
            </view>
            <view class="dept-info">
              <uni-icons type="home" size="14" color="#666"></uni-icons>
              <text>{{ item.dept?.deptName || '暂无部门' }}</text>
            </view>
            <view class="contact-info">
              <view class="phone-box" v-if="item.phonenumber">
                <uni-icons type="phone" size="14" color="#666"></uni-icons>
                <text>{{ item.phonenumber }}</text>
              </view>
              <view class="email-box" v-if="item.email">
                <uni-icons type="email" size="14" color="#666"></uni-icons>
                <text>{{ item.email }}</text>
              </view>
            </view>
          </view>
        </view>
        <view class="user-actions">
          <view class="action-btns">
            <button class="btn edit-btn" @tap.stop="handleEdit(item)">
              <uni-icons type="compose" size="14" color="#fff"></uni-icons>
              <text>编辑</text>
            </button>
            <view class="status-switch">
              <text class="status-label" :class="item.status === '0' ? 'text-success' : 'text-danger'">
                {{ item.status === '0' ? '已启用' : '已禁用' }}
              </text>
              <switch
                :checked="item.status === '0'"
                @change="handleStatusChange($event, item)"
                :disabled="item.admin"
                style="transform: scale(0.8);"
                color="#67c23a"
              />
            </view>
          </view>
          <view class="create-time">
            <uni-icons type="calendar" size="14" color="#999"></uni-icons>
            <text>{{ item.createTime }}</text>
          </view>
        </view>
      </view>

      <!-- 加载更多提 -->
      <uni-load-more :status="loadMoreStatus" :icon-size="16" :content-text="contentText" />
    </view>

    <!-- 空数据提示 -->
    <view v-else class="empty-box">
      <uni-icons type="info" size="50" color="#999"></uni-icons>
      <text class="empty-text">暂无用户数据</text>
    </view>
  </view>
</template>

<script>
import { listUser, changeUserStatus } from '@/api/system/user'
import defaultAvatar from '@/static/images/profile.jpg'

export default {
  data() {
    return {
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userName: undefined,
        nickName: undefined,
        phonenumber: undefined,
        status: undefined
      },
      userList: [],
      defaultAvatar,
      loading: false,
      hasMore: true,
      total: 0,
      loadMoreStatus: 'more',
      contentText: {
        contentdown: '上拉显示更多',
        contentrefresh: '正在加载...',
        contentnomore: '没有更多数据了'
      },
      statusOptions: [
        { label: '全部', value: '' },
        { label: '正常', value: '0' },
        { label: '停用', value: '1' }
      ],
      statusIndex: 0,
      refreshTimer: null
    }
  },
  onLoad() {
    this.getList()
  },
  onShow() {
    if (this.refreshTimer) {
      clearTimeout(this.refreshTimer)
      this.refreshTimer = null
      this.handleQuery()
    }
  },
  // 添加下拉刷新和上拉加载的页面生命周期
  onPullDownRefresh() {
    this.queryParams.pageNum = 1
    this.userList = []
    this.hasMore = true
    this.getList('refresh')
  },
  onReachBottom() {
    if (this.hasMore && !this.loading) {
      this.queryParams.pageNum++
      this.getList('more')
    }
  },
  methods: {
    async getList(type = 'more') {
      if (this.loading) return
      this.loading = true

      try {
        const params = Object.keys(this.queryParams).reduce((acc, key) => {
          if (this.queryParams[key] !== undefined && this.queryParams[key] !== '') {
            acc[key] = this.queryParams[key]
          }
          return acc
        }, {})

        const res = await listUser(params)

        if (res.code === 200) {
          const { rows, total } = res

          if (type === 'refresh' || params.pageNum === 1) {
            this.userList = rows
          } else {
            this.userList = [...this.userList, ...rows]
          }

          this.total = total
          this.hasMore = this.userList.length < total
          this.loadMoreStatus = this.hasMore ? 'more' : 'noMore'
        }
        return res
      } catch (error) {
        this.loadMoreStatus = 'more'
        uni.showToast({
          title: '获取用户列表失败',
          icon: 'none'
        })
        throw error
      } finally {
        this.loading = false
        if (type === 'refresh') {
          uni.stopPullDownRefresh()
        }
      }
    },

    // 搜索
    handleQuery() {
      this.queryParams.pageNum = 1
      this.userList = []
      this.hasMore = true
      this.loadMoreStatus = 'more'
      return this.getList('refresh')
    },

    async handleStatusChange(e, row) {
      const status = e.detail.value ? "0" : "1"
      try {
        await changeUserStatus(row.userId, status)
        uni.showToast({
          title: '修改成功',
          icon: 'success'
        })
        row.status = status
      } catch (error) {
        uni.showToast({
          title: '修改失败',
          icon: 'none'
        })
      }
    },

    handleViewDetail(user) {
      uni.navigateTo({
        url: `/pages/system/user/detail?userId=${user.userId}`
      })
    },

    // 新增用户
    handleAdd() {
      uni.navigateTo({
        url: '/pages/system/user/form'
      })
    },
    // 编辑用户
    handleEdit(user) {
      this.refreshTimer = setTimeout(() => {}, 100)
      uni.navigateTo({
        url: `/pages/system/user/form?userId=${user.userId}`
      })
    },
    // 状态选择改变
    handleStatusChange(e) {
      this.statusIndex = e.detail.value
      this.queryParams.status = this.statusOptions[this.statusIndex].value
    },

    // 重置查询
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        userName: undefined,
        nickName: undefined,
        phonenumber: undefined,
        status: undefined
      }
      this.statusIndex = 0
      this.handleQuery()
    }
  }
}
</script>

<style lang="scss">
.user-container {
  min-height: 100vh;
  background-color: #f5f7fa;
  padding: 20rpx;

  .search-box {
    background-color: #fff;
    border-radius: 16rpx;
    padding: 24rpx;
    margin-bottom: 20rpx;
    box-shadow: 0 2rpx 12rpx rgba(0,0,0,0.05);

    .search-form {
      .search-item {
        display: flex;
        align-items: center;
        margin-bottom: 20rpx;

        &:last-child {
          margin-bottom: 0;
        }

        .label {
          width: 140rpx;
          font-size: 28rpx;
          color: #606266;
          font-weight: 500;
        }

        input {
          flex: 1;
          height: 72rpx;
          background-color: #f8f9fa;
          border-radius: 8rpx;
          padding: 0 24rpx;
          font-size: 28rpx;
          color: #2c3e50;

          &::placeholder {
            color: #909399;
          }
        }

        .picker-box {
          flex: 1;
          height: 72rpx;
          background-color: #f8f9fa;
          border-radius: 8rpx;
          padding: 0 24rpx;
          font-size: 28rpx;
          display: flex;
          align-items: center;
          justify-content: space-between;

          text {
            color: #2c3e50;

            &.placeholder {
              color: #909399;
            }
          }

          .uni-icons {
            margin-left: 12rpx;
          }
        }
      }
    }

    .btn-group {
      display: flex;
      gap: 20rpx;
      margin-top: 30rpx;
      padding-top: 30rpx;
      border-top: 2rpx solid #f0f0f0;

      .btn {
        flex: 1;
        height: 80rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 12rpx;
        font-size: 28rpx;
        border-radius: 8rpx;
        transition: all 0.3s;

        &:active {
          transform: scale(0.98);
          opacity: 0.9;
        }

        &.search-btn {
          background-color: #409eff;
          color: #fff;

          &:active {
            background-color: #3a8ee6;
          }
        }

        &.reset-btn {
          background-color: #f5f7fa;
          color: #606266;
          border: 2rpx solid #dcdfe6;

          &:active {
            background-color: #e9e9eb;
          }
        }

        &.add-btn {
          background-color: #67c23a;
          color: #fff;

          &:active {
            background-color: #5daf34;
          }
        }
      }
    }
  }

  .user-list {
    .user-item {
      background-color: #fff;
      padding: 32rpx;
      margin-bottom: 24rpx;
      border-radius: 16rpx;
      box-shadow: 0 2rpx 12rpx rgba(0,0,0,0.05);

      .user-info {
        display: flex;
        margin-bottom: 24rpx;

        .avatar {
          width: 108rpx;
          height: 108rpx;
          border-radius: 54rpx;
          margin-right: 24rpx;
          border: 2rpx solid #eee;
        }

        .info-content {
          flex: 1;

          .name-row {
            margin-bottom: 16rpx;

            .username {
              font-size: 34rpx;
              font-weight: 600;
              color: #2c3e50;
              letter-spacing: 0.5rpx;
            }

            .nickname {
              font-size: 28rpx;
              color: #606266;
              margin-left: 16rpx;
              font-weight: 400;
            }
          }

          .dept-info {
            display: flex;
            align-items: center;
            margin-bottom: 14rpx;
            font-size: 26rpx;
            color: #606266;
            line-height: 1.4;

            .uni-icons {
              margin-right: 10rpx;
              color: #909399;
            }
          }

          .contact-info {
            display: flex;
            flex-wrap: wrap;
            gap: 20rpx;
            font-size: 26rpx;
            color: #606266;
            line-height: 1.4;

            .phone-box, .email-box {
              display: flex;
              align-items: center;

              .uni-icons {
                margin-right: 8rpx;
                color: #909399;
              }
            }
          }
        }
      }

      .user-actions {
        border-top: 1rpx solid #ebeef5;
        padding-top: 24rpx;
        margin-top: 8rpx;
        display: flex;
        justify-content: space-between;
        align-items: center;

        .action-btns {
          display: flex;
          align-items: center;
          gap: 28rpx;

          .btn {
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8rpx;
            font-size: 26rpx;
            padding: 12rpx 28rpx;
            border-radius: 32rpx;
            border: none;
            line-height: 1.4;
            transition: all 0.3s;

            &:active {
              opacity: 0.8;
            }
          }

          .edit-btn {
            background-color: #409eff;
            color: #fff;
            font-weight: 500;
            box-shadow: 0 2rpx 6rpx rgba(64,158,255,0.2);
          }

          .status-switch {
            display: flex;
            align-items: center;
            gap: 12rpx;

            .status-label {
              font-size: 26rpx;
              color: #666;

              &.text-success {
                color: #67c23a;
              }

              &.text-danger {
                color: #f56c6c;
              }
            }
          }
        }

        .create-time {
          display: flex;
          align-items: center;
          gap: 8rpx;
          font-size: 24rpx;
          color: #909399;

          .uni-icons {
            margin-right: 4rpx;
          }
        }
      }
    }
  }

  .empty-box {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 120rpx 0;
    background-color: #fff;
    border-radius: 16rpx;
    margin-top: 24rpx;

    .empty-text {
      margin-top: 24rpx;
      font-size: 28rpx;
      color: #909399;
      letter-spacing: 1rpx;
    }
  }
}
</style>